<?php

namespace app\api\controller\v50;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\live\LiveGift;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\zlcr2\Zlcr2QuestionUserView;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\zlcr3\Zlcr3Follow;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrAstrConsultActiveReplyRecord;
use app\common\lib\Util;
use app\zyhsapi\model\ZyhsConfig;
use app\zyhsapi\model\ZyhsConsultAstrData;
use app\zyhsapi\model\ZyhsConsultChatRecord;
use app\zyhsapi\model\ZyhsConsultRtcUserBenefits;
use think\Cache;
use think\Config;
use think\response\Json;

class ConsultChat extends Auth2
{
    private $appType2 = 2;

    /**
     * 获取 连线咨询新消息数量
     * @return Json
     * @throws \Exception
     */
    public function getNewMsgNum()
    {
        $resData = [
            'is_new_msg' => 0,
            'consult_new_msg_num' => 0,
        ];
        if ($this->user)
        {
            $newMsg = 0;
            //  服务 小红点------
            do
            {   // 未读 消息数量
                if ((new Zlcr2UserQuestion())->getUserUnReadIds($this->user['id']))
                {   // 未读问题ids
                    $newMsg = 1;
                    break;
                }
                if ((new Zlcr2QuestionUserView())->getUserUnReadViewIds($this->user['id']))
                {   // 未读蹭看ids
                    $newMsg = 1;
                    break;
                }
            } while (false);
            $resData['is_new_msg'] = $newMsg;
            // 连线咨询 未读消息数量
            $resData['consult_new_msg_num'] = (new ZyhsConsultChatRecord())->getUserUnreadAllNum($this->appType2, $this->user['id']);
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 专区咨询师列表
     * @return Json
     * @throws \Exception
     */
    public function getConsultAstrList(): Json
    {
        $type = input('type/d', 0);
        $page = input('page/d', 1);
        if (!in_array($type, [0, -1], true))
        {
            return show(config('code.error'), '未知的专区');
        }
        $zoneList = Config::Load(APP_PATH . 'zyhsapi/extra/consult_zone.php', 'consult_zone', 'zyhs');;
        // 获取 占星师 热的信息
        $astrHotData = (new ZyhsConsultAstrData())->getRankingList(2);
        //获取当前专区的咨询师列表
        $consultModel = new Zlcr3ConsultAccount();
        $zyhsRtcConfig = (new ZyhsConfig())->configInfo('rtc');
        if ($type === -1)
        {
            $pageData = (new Zlcr3Follow())->userFollowInfo($this->user['id'], $page);
            $pageData['data'] = array_keys($pageData['data']);
        } else
        {
            if (Util::ZyhsIsHuaweiOrHonorOrOppoHg($this->appType2))
            {   // 华为 合规情况 只显示 当前占星师数据
                if (Util::IsHuaweiAndOppo())
                {
                    $astrIdList = $zyhsRtcConfig['huawei_hg_consult_astr_ids'] ? explode(',', $zyhsRtcConfig['huawei_hg_consult_astr_ids']) : [];
                } else
                {
                    $astrIdList = $zyhsRtcConfig['honor_hg_consult_astr_ids'] ? explode(',', $zyhsRtcConfig['honor_hg_consult_astr_ids']) : [];
                }
                $total = count($astrIdList);
                $pageData = [
                    'total' => $total,// 记录总数
                    'per_page' => 100000,// 每页多少条
                    'current_page' => 1,// 当前页数
                    'last_page' => 1,// 总页数
                    'data' => [],
                ];

                foreach ($astrIdList as $astrIdItem)
                {
                    if (!isset($astrHotData[$astrIdItem]))
                    {
                        $astrHotData[$astrIdItem] = 0;
                    }
                    $pageData['data'][] = (int)$astrIdItem;
                }
            } else
            {
                $pageData = $consultModel->getChatConsultIds(0, $page, 100000);
            }
            $giftData = [
                'icon' => '/test/consult_chat/index/consult_gift_icon.png',
                'target' => 'local',
                'link' => 'consult_gift_pack_index?need_auth=0',
            ];
            $toolList = [
                [
                    'icon' => '/test/consult_chat/index/ai_chat.png',
                    'name' => 'AI提问',
                    'bg_color' => '#E9FFFF',
                    'border_color' => '#DBFAFA',
                    'target' => 'local',
                    'link' => 'aichat?type=0&need_auth=0',
                ], [
                    'icon' => '/test/consult_chat/index/question_answer.png',
                    'name' => '悬赏问答',
                    'bg_color' => '#EAF5FF',
                    'border_color' => '#DFEEF9',
                    'target' => 'local',
                    'link' => 'question_answer_index?need_auth=0',
                ], [
                    'icon' => '/test/consult_chat/index/consult_chat_icon.png',
                    'name' => '一键连线',
                    'bg_color' => '#E8FFF9',
                    'border_color' => '#D6F6ED',
                    'target' => 'local',
                    'link' => 'consult_astr_ask?need_auth=2',
                ],
            ];
        }
        // 过滤 测试咨询师
        $testAstrIds = isset($zyhsRtcConfig['consult_test_astr_id']) && $zyhsRtcConfig['consult_test_astr_id'] ? explode(',', $zyhsRtcConfig['consult_test_astr_id']) : [];
        $testAstrIds = array_map('intval', $testAstrIds);
        $astrIdsLimit = [];
        foreach ($pageData['data'] as $astrIdItem)
        {
            if (!in_array($astrIdItem, $testAstrIds, true))
            {
                $astrIdsLimit[] = $astrIdItem;
            }
        }
        //获取分页后的数据
        $astrConsultInfos = $consultModel->batchGetInfoByIds($astrIdsLimit, ['zone_tids', 'service_duration', 'recommended_nums', 'status', 'tids', 'tags', 'level']);
        $astrInfo = (new ZlcrAstr())->batchGetInfoByIds($astrIdsLimit);
        $astrList1 = [];
        $astrList2 = [];
        $workIntro = "";
        if (Util::ZyhsIsHuaweiOrHonorOrOppoHg($this->appType2))
        {
            if (Util::IsHuaweiAndOppo())
            {
                if (isset($zyhsRtcConfig['huawei_work_intro']) && $zyhsRtcConfig['huawei_work_intro'])
                {
                    $workIntro = $zyhsRtcConfig['huawei_work_intro'];
                }
            } else
            {
                if (isset($zyhsRtcConfig['honor_work_intro']) && $zyhsRtcConfig['honor_work_intro'])
                {
                    $workIntro = $zyhsRtcConfig['honor_work_intro'];
                }
            }
        }
        // 获取新人福利 免充值 发起连线
        $newUserWelfare = $this->user ? (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType2, $this->user['id']) : null;
        $freeRtcDuration = $newUserWelfare ? (($newUserWelfare['min'] ?? 0) * 60) : 0;
        // 免费 连线 时长
        $freeConsultDuration = $freeRtcDuration > 0 ? 1 : 0;
        if ($freeConsultDuration > 0)
        {
            $consultBtnName = sprintf("免费连线%d分钟", (int)($freeRtcDuration / 60));
        } else
        {
            $consultBtnName = '现在连线';
        }
        $ActiveReplyNumData = (new ZlcrAstrConsultActiveReplyRecord())->getActiveReplyData();
        foreach ($astrHotData as $astrId => $s)
        {   // 热度榜遍历
            if (!isset($astrConsultInfos[$astrId]))
            {
                continue;
            }
            $item = $astrConsultInfos[$astrId];
            $tips1 = '';
            $tips2 = '';
            $tips3 = '';
            if ($item['service_duration'])
            {
                $tips1 = '服务' . ceil($item['service_duration'] / 60) . '分钟';
            }
            if ($item['recommended_nums'])
            {
                $tips2 = '推荐' . $item['recommended_nums'];
            }
            $activeReplyNum = $ActiveReplyNumData[$astrId] ?? 0;
            if ($activeReplyNum)
            {
                $tips3 = '积极回复' . $activeReplyNum;
            }
            $tagData = [];
            $zoneArr = [];
            foreach ($zoneList as $zone)
            {
                if ($zone['status'] && in_array($zone['type'], $item['zone_tids'], true))
                {
                    $zoneArr[] = $zone['name'];
                    if (count($zoneArr) >= 2)
                    {
                        break;
                    }
                }
            }
            if ($zoneArr)
            {
                $tagData[] = '擅长：' . implode(' ', $zoneArr);
            }
            $tagsArr = $consultModel->getTags($item['tags']);
            if (Util::ZyhsIsHuaweiOrHonorOrOppoHg($this->appType2))
            {
                $tagsArr = array_values(array_diff($tagsArr, ['星盘']));
            }
            if ($this->headers['app-type'] === 'android')
            {
                foreach ($tagsArr as $k => $tagItem)
                {
                    if ($tagItem === '星盘')
                    {
                        $tagsArr[$k] = '星图';
                    }
                }
            }
            if ($tagsArr)
            {
                $tagData[] = '技能：' . implode(' ', $tagsArr);
            }
            if ($item['status'] == 1)
            {   // 在线
                $astrList1[] = [
                    'name' => $astrInfo[$astrId]['nickname'],
                    'avatar' => $astrInfo[$astrId]['avatar'],
                    'tags_icon' => $consultModel->getTagsIcon($item['tids']),
                    'tags' => $tagData,
                    'des' => $workIntro ?: $astrInfo[$astrId]['work_intro'],
                    'status' => 1,
                    'id' => $astrId,
                    'tips1' => $tips1 ?? '',
                    'tips2' => $tips2 ?? '',
                    'tips3' => $tips3 ?? '',
                    'level' => $item['level'],
                    'btn_data' => [['title' => '私聊', 'type' => 1,], ['title' => $consultBtnName, 'type' => 2,],],
                ];
            } else
            {   // 休息
                $astrList2[] = [
                    'name' => $astrInfo[$astrId]['nickname'],
                    'avatar' => $astrInfo[$astrId]['avatar'],
                    'tags_icon' => $consultModel->getTagsIcon($item['tids']),
                    'tags' => $tagData,
                    'des' => $workIntro ?: $astrInfo[$astrId]['work_intro'],
                    'status' => 2,
                    'id' => $astrId,
                    'tips1' => $tips1 ?? '',
                    'tips2' => $tips2 ?? '',
                    'tips3' => $tips3 ?? '',
                    'level' => $item['level'],
                    'btn_data' => [['title' => '私聊', 'type' => 1,],],
                ];
            }
        }
        $pageData['data'] = array_merge($astrList1, $astrList2);
        //  弹窗 ---------
        if ($type >= 0 && $page === 1)
        {
            $benefitsCacheKey = 'reg_user_send_benefits_' . date('Ymd') . ':' . $this->user['id'];
            if (!Cache::get($benefitsCacheKey, false))
            {
                Cache::set($benefitsCacheKey, 1, 86400);    // 今日已经 弹了提示 不再弹了
                // 获取 用户 当前的福利信息
                $zyhsConsultRtcUserBenefitsModel = new ZyhsConsultRtcUserBenefits();
                $newUserWelfare = $zyhsConsultRtcUserBenefitsModel->getConsultRtcUserBenefits($this->appType2, $this->user['id']);
                if ($newUserWelfare && isset($newUserWelfare['min']) && $newUserWelfare['min'])
                {
                    $expireTime = $this->request->time() + 259200;  // 3天后
                    if (isset($newUserWelfare['type']) && $newUserWelfare['type'] === 2 && $newUserWelfare['expire_time'] > $expireTime)
                    {   // 脚本 赠送   并且 过期时间 大于 3天 ，强制更新过期时间 为3天后
                        $zyhsConsultRtcUserBenefitsModel->updateData($newUserWelfare['id'], $this->appType2, $this->user['id'], ['expire_time' => $expireTime]);
                    }
                    $popWindows = Util::getZhunleConsultBenefitsConfig($newUserWelfare['min']);
                }
            }
        }
        $pageData['pop_windows'] = $popWindows ?? null;
        $pageData['gift_data'] = $giftData ?? null;
        $pageData['tool_list'] = $toolList ?? [];


        return show(config('code.success'), '请求成功', $pageData);
    }

    /**
     * 咨询师主页
     * @return Json
     * @throws \Exception
     */
    public function homePage()
    {
        $astrId = input('astr_id/d', 0);
        $zlcrAstrModel = new ZlcrAstr();
        $astrInfo = $zlcrAstrModel->getInfoById($astrId);
        if (!$astrInfo)
        {
            return show(config('code.error'), '咨询师不存在');
        }
        $res = $zlcrAstrModel->homePage2($astrInfo, 1, 2);
        if ($this->user)
        {
            $resData = (new Zlcr3Follow())->userFollowInfo($this->user['id'], -1);
            $followIds = array_keys($resData['data']);
            $followIds = $followIds ?: [];
            $newUserWelfare = (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType2, $this->user['id']);
            $res['btn_name'] = $newUserWelfare ? sprintf("免费连线%d分钟", $newUserWelfare['min'] ?? 0) : '现在连线';
        } else
        {
            $followIds = [];
            $res['btn_name'] = '现在连线';
        }
        $res['follow_status'] = in_array($astrId, $followIds, false) ? 1 : 2;

        return show(config('code.success'), '', $res);
    }

    /**
     * 咨询对话工具列表
     * @return Json
     */
    public function toolList()
    {
        $resData = [
            [
                'icon' => '/test/consult_chat/tool/tool_photo.png',
                'name' => '照片',
                'type' => 1,
            ], [
                'icon' => '/test/consult_chat/tool/tool_astr.png',
                'name' => $this->headers['app-type'] === 'ios' ? '星盘' : '星图',
                'type' => 2,
            ], [
                'icon' => '/test/consult_chat/tool/tool_sub.png',
                'name' => '预约咨询',
                'type' => 3,
            ], [
                'icon' => '/test/consult_chat/tool/tool_gift.png',
                'name' => '礼物',
                'type' => 4,
            ],
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取 咨询礼物列表
     * @return Json
     * @throws \Exception
     */
    public function getGiftList()
    {
        $giftList = (new LiveGift())->getListPage('', 'sort', [], 0);

        if ($this->user)
        {
            // 获取用户背包准币信息
            $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($this->user['id']);
            $coin = (int)($user_coin['balance'] ?? 0);
            $hasCoinPwd = $user_coin['password'] ? 1 : 0;
        } else
        {
            $coin = 0;
        }
        $resGiftList = [];
        foreach ($giftList['data'] as $giftDatum)
        {
            if ((int)$giftDatum['type'] === 1) continue;

            $resGiftList[] = [
                'id' => (int)$giftDatum['id'],
                'name' => $giftDatum['name'],
                'icon' => $giftDatum['img'],
                'coin' => (int)$giftDatum['coin'],
                'lottie' => $giftDatum['is_lottie'] > 0 ? json_decode($giftDatum['lottie'], true) : null,
            ];
        }
        return show(config('code.success'), '请求成功', [
            'gift_list' => $resGiftList,
            'coin' => $coin,
            'has_coin_pwd' => $hasCoinPwd ?? 0,
        ]);
    }
}